<?php

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      

//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/03/22
//      |_|                                         | TpMeCMS

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller\store;

use Imi\Db\Db;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;


/**
 * 店铺优惠券💶
 * @Auth(name="token",nologin={"get_coupons_list","get_coupons_data"})
 * @Controller("/store.coupons/")
 */
class Coupons extends StoreOwner
{
    protected $noNeedLogin = ['no'];
    protected $noNeedRight = ['*'];


    /**
     * 发布优惠券
     * @param string $name 优惠券名
     * @param string $type 类型:cash=代金券,discount=折扣券
     * @param string $type_status 类型:1=满减卷,2=复购卷,3=分享卷,4=抵扣卷,5=引流卷,6=商品卷,7=领劵中心卷
     * @param string $goods_ids 适用商品
     * @param float $jian 优惠面额
     * @param float $man 消费门槛
     * @param int $stock 库存
     * @param int $limit 每人限制
     * @param int $day 有效期天(2选1)
     * @param int $hour 小时
     * @param int $min 分钟
     * @param string $usetimestart 使用开始时间(2选1)
     *  @param string $usetimeend 使用到期时间(2选1)
     * @param string $description 描述
     * @param string $mix_status 混合付:1=不支持,2=支持
     * @param string $give_status 赠送:1=不支持,2=支持
     * @param string $scene 场景:current=通用,auction=拍卖,groupon=拼团,rice=米市,direct=直接付,scan=扫码付
     * @param string $get_status 领取状态:1=店铺指定,2=都可领取
     * @param int $repeat 复购次数
     * @param float $deduct 抵扣
     * @param float $return_shell 返贝壳
     * 
     * @return void
     * @Action
     */
    public function add_coupons($deduct = null, $return_shell = null, $hour = null,  $min = null, $repeat = null, $type = 'cash', $type_status = null, $name = null, $goods_ids = null, $jian = null, $man = null, $stock = null, $limit = null, $day = null, $usetimestart = null, $usetimeend = null, $description = null, $mix_status = null, $give_status = null, $scene = null, $get_status = null)
    {
        $this->init();

        //     `gettime` varchar(50) DEFAULT NULL COMMENT '领取周期',
        //     `day` varchar(50) DEFAULT NULL COMMENT '有效期',
        //     `description` varchar(255) DEFAULT NULL COMMENT '描述',
        //     `updatetime` int(11) DEFAULT NULL COMMENT '更新时间',
        //     `deletetime` int(11) DEFAULT NULL COMMENT '删除时间',
        //     `usetimestart` int(11) DEFAULT NULL,
        //     `usetimeend` int(11) DEFAULT NULL,
        //     `gettimestart` int(11) DEFAULT NULL,
        //     `gettimeend` int(11) DEFAULT NULL,
        //     PRIMARY KEY (`id`) USING BTREE
        //   ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COMMENT='优惠券';
        $scene = $scene ? $scene : 'current';
        $type_status = $type_status ? $type_status : '1';
        $type = $type ? $type : 'cash';
        if ($type == 'cash') {


            if ($jian > $man) {
                return $this->error('优惠额度不能大于满');
            }


            if ($goods_ids) {
                $price = Db::name('goodssku_price')->where('goods_id', '=', $goods_ids)->min('price');
                if ($jian > $price / 2) {
                    return $this->error('优惠额度不能大于商品价格一半', $price);
                }
                $data['goods_ids'] = $goods_ids;
            }
        }

        $s = 0;
        if ($day)
            $s += $day * 86400;
        if ($hour)
            $s += $hour * 3600;
        if ($min)
            $s += $min * 60;


        $data['type_status'] = $type_status;

        $data['get_status'] = $get_status;
        $data['scene'] = $scene;
        if(!$name){
            //场景:current=通用,auction=拍卖,groupon=拼团,rice=米市,direct=直接付,scan=扫码付
            switch ($scene) {
                case 'current':
                    $name = '通用券';
                    break;
                case 'auction':
                    $name = '拍卖券';
                    break;
                case 'groupon':
                    $name = '拼团券';
                    break;
                case 'rice':
                    $name = '米市券';
                    break;
                case 'direct':
                    $name = '直接付券';
                    break;
                case 'scan':
                    $name = '扫码付券';
                    break;
                
                default:

                    break;
            }
        }
        $data['name'] = $name;
     
        $data['type'] = $type;
        $data['s'] = $s;
        $data['repeat'] = $repeat;

        $data['jian'] = $jian;
        $data['man'] = $man;
        $data['stock'] = $stock;
        $data['limit'] = $limit;
        // $data['day'] = strtotime($day);
        if ($usetimestart)
            $data['usetimestart'] = strtotime($usetimestart);
        if ($usetimeend)
            $data['usetimeend'] = strtotime($usetimeend);

        // if ($data['usetimeend'] < time()) {
        //     return $this->error('结束时间已过');
        // }
        $data['day'] = $day;
        $data['hour'] = $hour;
        $data['min'] = $min;
        $data['description'] = $description;
        $data['mix_status'] = $mix_status ? $mix_status : '2';
        $data['give_status'] = $give_status ? $give_status : '1';

        $data['deduct'] = $deduct;//抵扣
        $data['return_shell'] = $return_shell;//返贝壳



        $data['store_id'] = $this->store_id;
        $data['createtime'] = time();
        $id = Db::name('coupons')->insert($data)->getLastInsertId();
        return $this->success('发布成功');
    }




    // /**
    //  * 获取最大的店铺优惠券
    //  *
    //  * @param int $goods_money 商品总价格
    //  * @param int $store_id 店铺id
    //  * @return void
    //  * @Action
    //  */
    // public function get_max_store_coupon($goods_money = 0, ?int $store_id)
    // {
    //     var_dump($goods_money, $this->auth->user()->id, $store_id);
    //     $coupon = $this->getMaxStoreCoupon($goods_money, $this->auth->user()->id, $store_id);
    //     return $this->success($goods_money, $coupon);
    // }


    /**
     * 给用户发优惠券
     * @param integer $coupons_id 用户优惠券
     * @param string $user_ids 用户ids
     * @return void
     * @Action
     */
    public function add_user_coupons($coupons_id = null, $user_ids)
    {
        $this->init();
        $coupons = $this->getCoupon($coupons_id);
        if ($coupons['store_id'] != $this->store_id) {
            return $this->error('非本店');
        }
        if ($coupons['stock'] < 1) {
            return $this->error('该优惠券库存不足');
        } else {
            $user_ids = explode(',', $user_ids);
            if ($coupons['stock'] < sizeof($user_ids)) {
                return $this->error('该优惠券库存不足' . sizeof($user_ids) . '张');
            }
        }

        // switch ($coupons['type_status']) {
        //     case '1':
        //         //类型:1=满减卷,2=复购卷,3=分享卷,4=抵扣卷,5=引流卷,6=商品卷,7=领劵中心卷

        //         break;

        //     case '6':
        //         //类型:1=满减卷,2=复购卷,3=分享卷,4=抵扣卷,5=引流卷,6=商品卷,7=领劵中心卷
        //         if (date('n') > 10) {
        //             return $this->error('该商品优惠券,只能在1-10号内领取');
        //         }
        //         break;
        //     default:
        //         # code...
        //         break;
        // }
        foreach ($user_ids as $key => $user_id) {
            $data['user_id'] = $user_id;
            $data['coupons_id'] = $coupons_id;

            // $count = Db::name('user_coupons')->whereEx($data)->count();
            // if ($count >= $coupons['limit']) {
            //     return $this->error('该优惠券限制每人' . $coupons['limit'] . '张');
            //     // var_dump('该优惠券限制每人' . $coupons_id);
            // }

            $data['createtime'] = time();
            if ($coupons['s'] > 0) {
                $end_time = time() + $coupons['s'];
            } else {
                $end_time = $coupons['usetimeend'];
            }
            $data['end_time'] = $end_time; //需要修改 根据类型判断
            $data['store_id'] = $coupons['store_id'];
            $data['status'] = '1';
            $data['get_status'] = '2'; //获取状态:1=领取,2=发放,3=转赠
            Db::name('user_coupons')->insert($data);
            //减少库存
            Db::name('coupons')->where('id', '=', $coupons_id)->setFieldDec('stock', 1)->update();
        }

        return $this->success('发放成功');
    }



    // /**
    //  * 获取最大的平台优惠券
    //  *
    //  * @param int $goods_money 商品总价格
    //  * @return void
    //  * @Action
    //  */
    // public function get_max_coupon($goods_money)
    // {
    //     $coupon = $this->getMaxCoupon($goods_money, $this->auth->user()->id);
    //     return $this->success($goods_money, $coupon);
    // }

    /**
     * 获取优惠券列表💶
     *
     * @param string $type_status 类型:1=满减卷,2=复购卷,3=分享卷,4=抵扣卷,5=引流卷,6=商品卷,7=领劵中心卷
     * @param integer $page 1
     * @param integer $limit 10
     * @param integer $goods_ids 商品id
     * @return void
     * @Action
     */
    public function get_coupons_list(?int $page = 1, ?int  $limit = 10, $date = null, $type_status = null, ?int $goods_ids = null)
    {
        $this->init();
        $page = $page ?: 1;
        $limit = $limit ?: 10;
        $data = [];
        if ($type_status)
            $data['type_status'] = $type_status;
        // if ($date) {
        //     $date = date('Y-m', strtotime($date));
        //     $e_date = date('Y-m-d 23:59:59', strtotime($date . " +1 month -1 day"));
        //     $data['createtime'] = ['between time', [$date, $e_date]];
        // }
        // 1=满减卷,2=复购卷,3=分享卷,4=抵扣卷,5=引流卷,6=商品卷,7=领劵中心卷

        $data['store_id'] = $this->store_id;
        if ($goods_ids)
            $data['goods_ids'] = $goods_ids;

        $list = Db::name('coupons')->whereEx($data)->whereIsNull('deletetime')->orderRaw('createtime desc')->page($page, $limit)->select()->getArray();
        if ($list)
            foreach ($list as $key => &$val) {
                $this->ChangeUserCouponsFieldData($val);
            }
        return $this->success('ok', $list);
    }


    /**
     * 更新优惠券库存💶
     *
     * @param int $id 优惠券id
     * @param int $stock 库存
     * @return void
     * @Action
     */
    public function update_coupons_stock($id = null,?int $stock=null)
    {
        $this->init();
        $data['id'] = $id;
        $data['store_id'] = $this->store_id;
        $coupons = Db::name('coupons')->whereEx($data)->whereIsNull('deletetime')->find();

        if (!$coupons) {
            return $this->error('没有该优惠券');
        }
        // $this->ChangeFieldData($res);
        switch ($coupons['status']) {
            case 'up':
                
                break;

            case 'halt':
            
                break;
            case 'down':
            
                    return $this->error('不能修改库存');
                
                break;
            default:
                # code...
                break;
        }
        Db::name('coupons')->whereEx($data)->setFieldInc('stock',$stock)->update();
  
        return $this->success('ok');
    }


    /**
     * 更新优惠券状态💶
     *
     * @param int $id 优惠券id
     * @param string $status 状态:up=上架,halt=暂停,down=下架
     * @return void
     * @Action
     */
    public function update_coupons_status($id = null,$status=null)
    {
        $this->init();
        $data['id'] = $id;
        $data['store_id'] = $this->store_id;
        $coupons = Db::name('coupons')->whereEx($data)->whereIsNull('deletetime')->find();

        if (!$coupons) {
            return $this->error('没有该优惠券');
        }
        // $this->ChangeFieldData($res);
        switch ($coupons['status']) {
            case 'up':
                
                break;

            case 'halt':
            
                break;
            case 'down':
                if($status=='up' || $status=='halt'){
                    return $this->error('不能再次修改状态');
                }
                break;
            default:
                # code...
                break;
        }
        Db::name('coupons')->whereEx($data)->update(['status'=>$status]);
  
        return $this->success('ok');
    }

    /**
     * 删除优惠券💶
     *
     * @param int $id 优惠券id
     * @return void
     * @Action
     */
    public function del_coupons($id = null)
    {
        $this->init();
        $data['id'] = $id;
        $data['store_id'] = $this->store_id;
        $coupons = Db::name('coupons')->whereEx($data)->find();

        if (!$coupons) {
            return $this->error('没有该优惠券');
        }
        // $this->ChangeFieldData($res);
        switch ($coupons['status']) {
            case 'up':
                return $this->error('结束后再删除');
                break;

            case 'halt':
                return $this->error('结束后再删除');
                break;
            case 'down':
  
                break;
            default:
                # code...
                break;
        }

        Db::name('coupons')->whereEx($data)->update(['deletetime'=>time()]);
  
        return $this->success('删除成功');
    }


    /**
     * 获取优惠券统计数💶
     *
     * @return void
     * @Action
     */
    public function get_coupons_count()
    {
        $this->init();
        $where['store_id'] = $this->store_id;
        $end = Db::name('coupons')->whereEx($where)->where('usetimeend', '>', 1)->whereIsNull('deletetime')->where('usetimeend', '<', time())->count();
        $count = Db::name('coupons')->whereEx($where)->whereIsNull('deletetime')->count();
        // $ing = Db::name('coupons')->whereEx($where)->where('usetimestart', '>', time())->count();
        $ing = $count - $end;



        $data['end'] = $end;
        $data['ing'] = $ing;
        $data['count'] = $count;
        return $this->success('ok', $data);
    }

    /**
     * 获取优惠券详情💶
     *
     * @param int $id 优惠券id
     * @return void
     * @Action
     */
    public function get_coupons_data($id = null)
    {
        $this->init();
        $data['id'] = $id;
        $data['store_id'] = $this->store_id;
        $res = Db::name('coupons')->whereEx($data)->find();
        if (!$res) {
            return $this->error('没有该优惠券');
        }
        $this->ChangeFieldData($res);
        return $this->success('ok', $res);
    }


    /**
     * 改变字段
     *
     * @param array $val 
     * @return void
     */
    protected function ChangeUserCouponsFieldData(&$val)
    {
        // $val['coupons'] = Db::name('coupons')->where('id', '=', $val['coupons_id'])->find();
        $val['date_str'] = $this->TimeToStr($val['createtime']);
        // $val['date'] = date('Y-m-d H:i:s', $val['end_time']);

        if ($val['usetimestart'] > 0)
            $val['usedate_start'] = date('Y-m-d', $val['usetimestart']);
        if ($val['usetimeend'] > 0)
            $val['usedate_end'] = date('Y-m-d', $val['usetimeend']);        

        if ($val['goods_ids'] > 0)
            $val['goods'] = Db::name('goods')->where('id', '=', $val['goods_ids'])->find();

        $val['give_num'] = Db::name('user_coupons')
            ->where('coupons_id', '=', $val['id'])
            ->count(); //赠送数量
        $val['use_num'] = Db::name('user_coupons')
            ->where('coupons_id', '=', $val['id'])
            ->where('status', '=', '2') //状态:1=待使用,2=已使用,3=已过期
            ->count(); //使用
        $val['unuse_num'] = Db::name('user_coupons')
            ->where('coupons_id', '=', $val['id'])
            ->where('status', '=', '1') //状态:1=待使用,2=已使用,3=已过期
            ->count(); //未使用
        $val['expire_num'] = Db::name('user_coupons')
            ->where('coupons_id', '=', $val['id'])
            ->where('status', '=', '3') //状态:1=待使用,2=已使用,3=已过期
            ->count(); //过期

        return $val;
    }


    /**
     * 获取用户信息
     *
     * @param int $user_id 用户id
     * @return void
     * @Action
     */
    public function get_user_data($user_id){
        $user = Db::name('user')->where('id','=',$user_id)->fieldRaw('nickname,avatar,id')->find();
        if($user){
            return $this->success('ok',$user);
        }
        return $this->error('没有');
    }


    /**
     * 改变字段
     *
     * @param array $val 
     * @return void
     */
    protected function ChangeFieldData(&$val)
    {
        $val['date_str'] = $this->TimeToStr($val['createtime']);
        $val['date'] = date('Y-m-d H:i:s', $val['createtime']);

        if ($val['usetimestart'] > 0)
            $val['usedate_start'] = date('Y-m-d', $val['usetimestart']);
        if ($val['usetimeend'] > 0)
            $val['usedate_end'] = date('Y-m-d', $val['usetimeend']);

        if ($val['goods_ids'] > 0)
            $val['goods'] = Db::name('goods')->fieldRaw('title,image')->where('id', '=', $val['goods_ids'])->find();
        $val['give_num'] = Db::name('user_coupons')
            ->where('coupons_id', '=', $val['id'])
            ->count(); //赠送数量
        $val['use_num'] = Db::name('user_coupons')
            ->where('coupons_id', '=', $val['id'])
            ->where('status', '=', '2') //状态:1=待使用,2=已使用,3=已过期
            ->count(); //使用
        $val['unuse_num'] = Db::name('user_coupons')
            ->where('coupons_id', '=', $val['id'])
            ->where('status', '=', '1') //状态:1=待使用,2=已使用,3=已过期
            ->count(); //未使用
        $val['expire_num'] = Db::name('user_coupons')
            ->where('coupons_id', '=', $val['id'])
            ->where('status', '=', '3') //状态:1=待使用,2=已使用,3=已过期
            ->count(); //过期

        return $val;
    }
}
